package com.deep.test.ximalaya;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * <p>Description:</p>
 * Created with IDEA
 * author:hudepin
 * createTime:2018/5/22 18:05
 */
public class IdGenerateImpl implements IdGenerate {
    private IdGenerateImpl() {
    }

    public static IdGenerateImpl getInstance() {
        return IdGenerateHolder.instance;
    }

    private static class IdGenerateHolder {
        public static final IdGenerateImpl instance = new IdGenerateImpl();
    }

    private static Map<String, AtomicLong> cacheMap = new ConcurrentHashMap<String, AtomicLong>();

    @Override
    public long nextId(String name) {
        AtomicLong uniqeid = cacheMap.get(name);
        if (uniqeid != null) {
            return uniqeid.getAndIncrement();
        } else {
            synchronized (this) {
                uniqeid = cacheMap.get(name);
                if (uniqeid != null) {
                    return uniqeid.getAndIncrement();
                }
                uniqeid = new AtomicLong(0);
                cacheMap.put(name, uniqeid);
                return uniqeid.getAndIncrement();
            }

        }
    }


}
